//
//  HPAccountIndexViewController.m
//  HPZZTong
//
//  Created by Handpay on 14-3-28.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPAccountIndexViewController.h"
#import "DefineUtil.h"
#import "LimitInfoData.h"


@interface HPAccountIndexViewController (){
    AccountInfoData* accountInfo;
    BOOL isNeedGoLimit;
    int refreshStatus;
    BOOL tableViewSelectEnable;
    
    CGRect accountFrame;
    CGRect shopNameFrame;
    
}
@property(nonatomic, retain)NSMutableArray* functionArray;
@property(nonatomic, retain)NSMutableArray* screenArray;
@property(nonatomic, retain)NSString* selectScr;

@end

@implementation HPAccountIndexViewController

#if ZZT_FOR_TEST
    #define parseValue(key)   [respData objectForKey:key];
#else
    #define parseValue(key)   DES_DEC([respData objectForKey:key]);
#endif

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hideBottomBar = NO;
        accountInfo = ZZT_CLIENG.accountInfo;
        isNeedGoLimit = NO;
        tableViewSelectEnable = YES;
    }
    return self;
}

- (void)initDataArray{
    tableViewSelectEnable = YES;
    self.functionArray = [NSMutableArray arrayWithArray:@[@"基本信息管理",@"刷卡器连接", @"帮助中心"]];
    self.screenArray = [NSMutableArray arrayWithArray:@[SCR_BASE_INFO_MANAGER,SCR_SWIPER_SELECT, SCR_HELP]];
    
    if (accountInfo.accountStatus != AccountStatusNotSubmit) {
        NSString* quality = SCR_REVIEW_STATE;
        
        [self.functionArray insertObject:@"收款限额" atIndex:1];
        [self.screenArray insertObject:SCR_ACCOUNT_LIMIT atIndex:1];
        
        [self.functionArray insertObject:@"收款提现" atIndex:1];
        [self.screenArray insertObject:SCR_WITHDRAW atIndex:1];
        
        if (accountInfo.accountStatus == AccountStatusSuccess) {
            
            [self.functionArray insertObject:@"收款卡管理" atIndex:1];
            
            [self.screenArray insertObject:SCR_CARDS_MANAGER atIndex:1];
            quality = SCR_QUALITY_CONFIRM;
        }
        
        [self.functionArray insertObject:@"资质信息" atIndex:1];
        [self.screenArray insertObject:quality atIndex:1];
    }
    
    CGRect tableFrame = self.functionTableView.frame;
    tableFrame.size.height = self.screenArray.count * 44 - 1;
    
    CGFloat yOffset = CGRectGetMaxY(tableFrame) - (ScreenHeight - TABBAR_HEIGHT - (iOS7Later ? 0 : HEIGHT_STATUS_BAR));
    if (yOffset > 0.f) {
        tableFrame.size.height -= yOffset;
        self.functionTableView.scrollEnabled = YES;
    }else{
        self.functionTableView.scrollEnabled = NO;
    }
    self.functionTableView.frame = tableFrame;
    [self.functionTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.amountLabel.textColor = kLightGreenFontColor;
    
    [self.submitButton setTitleColor:kTitleFontColor forState:UIControlStateNormal];
    [self.submitButton setTitleColor:kTitleFontColor forState:UIControlStateHighlighted];
    
    [self.submitButton setBackgroundImage:[[UIImage imageNamed:@"whitebutton.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateNormal];
    
    [self.submitButton setBackgroundImage:[[UIImage imageNamed:@"whitebuttonhover.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateHighlighted];
    
    self.accountLabel.text = [@"Hi," stringByAppendingString:accountInfo.account];
    
    self.functionTableView.dataSource = self;
    self.functionTableView.delegate = self;
    
    accountFrame = self.accountLabel.frame;
    shopNameFrame = self.shopNameLabel.frame;
    
    [self refreshDataAndUI];
    
    refreshStatus = -1;
    
    
    [NOTIFICATION addObserver:self selector:@selector(statusChanged:) name:AccountStatusChangeNotificationKey object:nil];
}


- (void)statusChanged:(NSNotification*)notification{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self refreshDataAndUI];
        [self sendLimitReq];
    });
}

- (void)refreshDataAndUI{
    [self treatShopHidden];
    [self initDataArray];
//    [self sendLimitReq];
}

- (void)treatShopHidden{
    if (accountInfo.accountStatus == AccountStatusNotSubmit) {
        self.limitView.hidden = self.shopNameLabel.hidden = YES;
        self.submitView.hidden = NO;
        self.accountLabel.numberOfLines = 1;
        [self.accountLabel sizeToFit];
    }else{
        self.limitView.hidden = self.shopNameLabel.hidden = NO;
        self.submitView.hidden = YES;
        self.shopNameLabel.text = accountInfo.shopName;
        [self resetAccountAndShopLabel];
    }
}

- (void)resetAccountAndShopLabel{
    self.accountLabel.numberOfLines = 0;
    self.accountLabel.frame = accountFrame;
    self.shopNameLabel.frame = shopNameFrame;
    
    [self.accountLabel sizeToFit];
    
    [self.shopNameLabel sizeToFit];
    
    CGFloat height = MAX(CGRectGetMaxY(self.accountLabel.frame), CGRectGetMaxY(self.shopNameLabel.frame));
    
    CGRect tempFrame = self.shopNameLabel.frame;
    tempFrame.origin.x = ScreenWidth - 20 - CGRectGetWidth(tempFrame);
    self.shopNameLabel.frame = tempFrame;
    
    tempFrame = self.lineView.frame;
    tempFrame.origin.y = height + 10;
    self.lineView.frame = tempFrame;
    
    tempFrame = self.limitView.frame;
    tempFrame.origin.y = CGRectGetMaxY(self.lineView.frame) + 15;
    self.limitView.frame = tempFrame;
    
    self.submitView.frame = tempFrame;
    
    tempFrame = self.logoutButton.frame;
    tempFrame.origin.y = CGRectGetMaxY(self.lineView.frame) + 1;
    self.logoutButton.frame = tempFrame;
}

- (void)sendLimitReq{
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    NSDictionary* params = @{@"phone": DES_ENC(accountInfo.mobile),
                             KEY_CHANNEL: [zzt getChannel],
                             @"appCode": @"1",
                             @"account":DES_ENC(zzt.accountInfo.account)};
    LOG(@"params:%@", params);
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_GET_LIMIT withData:@{@"dayLimit": @"5000", @"monthLimit": @"50000", @"debitCardLimit": @"120022", @"creditCardLimit": @"111111", @"dayTraffic": @"12345678", @"monthTraffic": @"1234444444400"}];
#else
    [zzt.netEngine sendRequest:NET_ACTION_GET_LIMIT withParams:params withDelegate:self];
    [zzt.uiEngine showNetWaiting];
#endif
}

- (void)sendCardInfoReq{
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    
    NSDictionary* params = @{KEY_ACCOUNT: DES_ENC(accountInfo.account),
                             KEY_CHANNEL: [zzt getChannel],
                             KEY_NEWBANK_FLAG: @"1"};
    LOG(@"params:%@", params);
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_MERCHANT_INFO withData:@{@"name": @"哈哈", @"certNo": @"32092219841021393X", @"bankName": @"中国银行", @"bankId": @"5", @"subBranchName": @"浦东第二支行", @"subBankId": @"2", @"cardNum": @"7777777777777714", @"status": @"03"}];
#else
    [zzt.netEngine sendRequest:NET_ACTION_MERCHANT_INFO withParams:params withDelegate:self];
    if (refreshStatus == 1 || refreshStatus == 2) {
        [zzt.uiEngine showNetWaiting];
    }
    
#endif
}

- (void)sendQualityInfoReq{
    ZZTongClientEngine* zzt = ZZT_CLIENG;

    NSDictionary* params = @{KEY_ACCOUNT: DES_ENC(accountInfo.account),
                             KEY_CHANNEL: [zzt getChannel],
                             KEY_NEWBANK_FLAG: @"1"};
    LOG(@"params:%@", params);
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_GET_AUDIT_INFO withData:@{@"auditInfo": @"怒啊实打实大大啊实打实打实大大声地啊实打实大大声地啊实打实大大声地啊实打实大大声地啊实打实大大声地啊实打实大大声地啊实大大声地啊实打实大大声地啊实打实大大声地声地", @"name": @"哈哈", @"certNo": @"32092219841021393X", @"bankName": @"中国银行", @"bankId": @"5", @"bankOfDeposit": @"浦东第二支行", @"subBankId": @"2", @"cardNum": @"7777777777777714", @"frontCCPicStatus": @"2", @"frontCCPic": @"http://www.baidu.com/img/bdlogo.gif", @"backCCPicStatus": @"0", @"backCCPic": @"http://www.baidu.com/img/bdlogo.gif", @"holdPicStatus": @"0", @"holdPic": @"http://www.baidu.com/img/bdlogo.gif", @"companyPicStatus": @"0", @"companyPic": @"http://www.baidu.com/img/bdlogo.gif", @"BLicensePicStatus": @"", @"BLicensePic": @"http://www.baidu.com/img/bdlogo.gif"}];

#else
    [zzt.netEngine sendRequest:NET_ACTION_GET_AUDIT_INFO withParams:params withDelegate:self];
//    [zzt.uiEngine showNetWaiting];
#endif
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.screenArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 130, 44)];
    desLabel.text = [self.functionArray objectAtIndex:indexPath.row];
    desLabel.font = kNormalFont;
    desLabel.textColor = kNormalFontColor;
    [cell addSubview:desLabel];
    [desLabel release];
    
    if ([desLabel.text isEqualToString:@"资质信息"]) {
        if (accountInfo.accountStatus == AccountStatusFailed){
            [self createStatusDesLabel:cell text:@"审核未通过" textColor:kRedFontColor];
        }else if (accountInfo.accountStatus == AccountStatusReview) {
            [self createStatusDesLabel:cell text:@"审核中" textColor:kLicFontColor];
        }
    }
    
    return [cell autorelease];
}

- (void)createStatusDesLabel:(UITableViewCell*)cell text:(NSString*)text textColor:(UIColor*)color{
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 0, 130, 44)];
    desLabel.text = text;
    desLabel.textAlignment = NSTextAlignmentRight;
    desLabel.font = kNormalFont;
    desLabel.textColor = color;
    [cell addSubview:desLabel];
    [desLabel release];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!tableViewSelectEnable) {
        return;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString* scrName = [self.screenArray objectAtIndex:indexPath.row];
    self.selectScr = scrName;
    if ([scrName isEqualToString:SCR_CARDS_MANAGER]){
        if (refreshStatus == -1) {
            refreshStatus = 2;
            [self sendCardInfoReq];
            return;
        }
    }else if ([scrName isEqualToString:SCR_REVIEW_STATE]
              || [scrName isEqualToString:SCR_QUALITY_INDEX]
              || [scrName isEqualToString:SCR_QUALITY_CONFIRM]){
        if (refreshStatus == -1) {
            refreshStatus = 1;
            [self sendCardInfoReq];
        }
        return;
    }else if([scrName isEqualToString:SCR_SWIPER_SELECT]){
        [SWIPERENG selectSwiperAndGetCsn:^(HPSwiperResult *swiperResult) {
            [CSNValidator validateCSNAndExcuteBlock:^(HPSwiperResult *swiperResult) {
                if (![HPUIENG doCheckGPSStatus] || [NSString isNilOrEmpty:[CSNValidator getLocation]])
                {
                    return;
                }
                if (swiperResult.isSuccess) {
                    [HPUIENG showAlert:@"刷卡器已连接"];
                }else{
                    
                }
            } autoTip:YES];
        } isShow:YES];
        return;
    }else if([scrName isEqualToString:SCR_WITHDRAW]){
        NSString* subWd = nil;
        if (![NSString isNilOrEmpty:accountInfo.wdPermission]) {
            subWd = [accountInfo.wdPermission substringToIndex:1];
        }
        if((accountInfo.accountStatus != AccountStatusSuccess) || [NSString isNilOrEmpty:subWd] || (![subWd isEqualToString:@"1"])){
            [HPUIENG showAlert:@"资质审核通过且有提现权限方可使用"];
            return;
        }
    }
    tableViewSelectEnable = NO;
    [HPUIENG showScreen:scrName];
}

- (void)dealloc {
    [NOTIFICATION removeObserver:self];
    accountInfo = nil;
    
    [_accountLabel release];
    [_shopNameLabel release];
    [_logoutButton release];
    [_limitView release];
    [_submitView release];
    [_amountLabel release];
    [_submitButton release];
    [_functionTableView release];
    [_lineView release];
    [_selectScr release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setAccountLabel:nil];
    [self setShopNameLabel:nil];
    [self setLogoutButton:nil];
    [self setLimitView:nil];
    [self setSubmitView:nil];
    [self setAmountLabel:nil];
    [self setSubmitButton:nil];
    [self setFunctionTableView:nil];
    [self setLineView:nil];
    [super viewDidUnload];
}

- (IBAction)logoutButtonClick:(id)sender {
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    
    NSDictionary* params = @{KEY_ACCOUNT: DES_ENC(accountInfo.account),
                             KEY_CHANNEL: [zzt getChannel]};
    LOG(@"params:%@", params);
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_LOGOUT withData:nil];
#else
    [zzt.netEngine sendRequest:NET_ACTION_LOGOUT withParams:params withDelegate:self];
    [zzt.uiEngine showNetWaiting];
#endif
    
}

- (IBAction)submitButtonClick:(id)sender {
    [ZZT_CLIENG submitQuality];
}

- (void)parseLimitInfo:(NSDictionary *)respData{
    LimitInfoData* limitInfo = [[LimitInfoData alloc] init];

    limitInfo.dayLimit = [respData objectForKey:@"dayLimit"];;
    limitInfo.monthLimit = [respData objectForKey:@"monthLimit"];;
    limitInfo.debitCardLimit = [respData objectForKey:@"debitCardLimit"];;
    limitInfo.creditCardLimit = [respData objectForKey:@"creditCardLimit"];;
    
    limitInfo.dayTraffic = [respData objectForKey:@"dayTraffic"];
    limitInfo.monthTraffic = [respData objectForKey:@"monthTraffic"];
    
    limitInfo.dayMagLimit = [respData objectForKey:@"dayMagLimit"];
    limitInfo.monthMagLimit = [respData objectForKey:@"monthMagLimit"];
    
    limitInfo.icDebitCardLimit = [respData objectForKey:@"icDebitCardLimit"];
    limitInfo.icCreditCardLimit = [respData objectForKey:@"icCreditCardLimit"];

    accountInfo.cardTranferLimitInfo = limitInfo;
    [limitInfo release];
    
    //收款提现权限
    accountInfo.wdPermission = [respData objectForKey:@"wdPermission"];
    
    dispatch_async(dispatch_get_main_queue(), ^(){
        NSString* amount = [Utility getFormatMoneyNoSymbol:accountInfo.cardTranferLimitInfo.dayTraffic];
        self.amountLabel.text = [Utility formatAmount2:amount];
    });
}

- (void)parseBankInfo:(NSDictionary *)respData{
    accountInfo.name = parseValue(@"name");
    accountInfo.certNo = parseValue(@"certNo");
    accountInfo.bankName = parseValue(@"bankName");
    accountInfo.bankId = [respData objectForKey:@"bankCode"];
    
    accountInfo.branchBankName = parseValue(@"subBranchName");
    accountInfo.branchBankId = [respData objectForKey:@"subBankCode"];
    accountInfo.cardNo = parseValue(@"cardNum");
    accountInfo.provinceId = [respData objectForKey:@"provinceId"];
    accountInfo.provinceName = parseValue(@"provinceName");
    accountInfo.areaId = [respData objectForKey:@"areaId"];
    accountInfo.areaName = parseValue(@"areaName");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [ZZT_UIENG hideNavigationBar:YES];
    
    self.tabBarController.tabBar.hidden = NO;
    
    if (accountInfo.accountStatus != AccountStatusNotSubmit){
        if ([NSString isNilOrEmpty:self.selectScr] || (![NSString isNilOrEmpty:self.selectScr] && ![self.selectScr isEqualToString:SCR_SWIPER_SELECT])) {
            [self sendLimitReq];
            [ZZT_UIENG getCurrentNavigation].tabBarController.view.userInteractionEnabled = NO;
            self.view.userInteractionEnabled = NO;
        }
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.selectScr = nil;
    tableViewSelectEnable = YES;
    [ZZT_UIENG hideNavigationBar:YES];}

- (PhotoStatus)parsePhontStauts:(NSString*)status{
    if ([status isEqualToString:@"1"]) {
        return PhotoStatusSuccess;
    }else if ([status isEqualToString:@"0"]) {
        return PhotoStatusReview;
    }else if ([status isEqual:@"2"]) {
        return PhotoStatusFailed;
    }
    
    return PhotoStatusNotSubmit;
}

- (void)parseAuditInfo:(NSDictionary *)respData{
    accountInfo.statusDescpriction = [respData objectForKey:@"auditInfo"];
    accountInfo.frontCCPicStatus = [self parsePhontStauts:[respData objectForKey:@"frontCCPicStatus"]];
    accountInfo.frontCCPicUrl = [respData objectForKey:@"frontCCPic"];
    
    accountInfo.backCCPicStatus = [self parsePhontStauts:[respData objectForKey:@"backCCPicStatus"]];
    accountInfo.backCCPicUrl = [respData objectForKey:@"backCCPic"];
    
    accountInfo.holdPicStatus = [self parsePhontStauts:[respData objectForKey:@"holdPicStatus"]];
    accountInfo.holdPicUrl = [respData objectForKey:@"holdPic"];
    
    accountInfo.companyPicStatus = [self parsePhontStauts:[respData objectForKey:@"companyPicStatus"]];
    accountInfo.companyPicUrl = [respData objectForKey:@"companyPic"];
    
    accountInfo.licensePicStatus = [self parsePhontStauts:[respData objectForKey:@"BLicensePicStatus"]];
    accountInfo.licensePicUrl = [respData objectForKey:@"BLicensePic"];
}

- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    
    if ([action isEqualToString:NET_ACTION_LOGOUT]) {
        [HPUIENG removeWaiting];
        [ZZT_CLIENG clearAccountInfo];
        [SwiperService setCsnStatus:CSNStatusNone];
        [HPUIENG popScreen];
    }else if ([action isEqualToString:NET_ACTION_GET_LIMIT]) {
        [self parseLimitInfo:respData];
        if (accountInfo.accountStatus == AccountStatusReview) {
            refreshStatus = 0;
            [self sendCardInfoReq];
        }else{
            [HPUIENG removeWaiting];
        }
    }else if ([action isEqualToString:NET_ACTION_MERCHANT_INFO]) {
        [self parseBankInfo:respData];
        dispatch_async(dispatch_get_main_queue(), ^{
            [ZZT_UIENG getCurrentNavigation].tabBarController.view.userInteractionEnabled = YES;
            self.view.userInteractionEnabled = YES;
        });
        
        NSString *status = [respData objectForKey:@"status"];
        [accountInfo setstatusByStr:status];
        if (refreshStatus == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [ZZT_UIENG getCurrentNavigation].tabBarController.view.userInteractionEnabled = NO;
                self.view.userInteractionEnabled = NO;
            });
            
            [self sendQualityInfoReq];
        }else if(refreshStatus == 2){
            [HPUIENG removeWaiting];
            refreshStatus = -1;
            [HPUIENG showScreen:SCR_CARDS_MANAGER];
        }else if(refreshStatus == 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [HPUIENG removeWaiting];
                [self refreshDataAndUI];
                refreshStatus = -1;
            });
        }else{
             [HPUIENG removeWaiting];
        }

    }else if ([action isEqualToString:NET_ACTION_GET_AUDIT_INFO]){
        
        [HPUIENG removeWaiting];
        refreshStatus = -1;
        [self parseBankInfo:respData];
        [self parseAuditInfo:respData];
        accountInfo.branchBankName = parseValue(@"bankOfDeposit");
        
        [HPUIENG showScreen:[self.screenArray objectAtIndex:1]];
    }else{
         [HPUIENG removeWaiting];
    }
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    refreshStatus = -1;
    if ([action isEqualToString:NET_ACTION_GET_LIMIT]) {
        ZZT_CLIENG.accountInfo.cardTranferLimitInfo = nil;
    }
}
@end
